# -*- coding: utf-8 -*-
# @时间：2023/11/2 19:56
# @作者：CJiaの可乐哥
# @文件名：cj_ninja
# @软件：Pycharm2023
from typing import Any, List

from django.db.models import QuerySet
from django.http import HttpRequest, HttpResponse
from ninja import NinjaAPI, Schema, Field
from ninja.types import DictStrAny
from ninja.pagination import PaginationBase


class CjNinjaAPI(NinjaAPI):
    def create_response(
            self,
            request: HttpRequest,
            data: Any,
            *,
            status: int = 200,
            code: int = 200,
            msg: str = "success",
            temporal_response: HttpResponse = None,
    ) -> HttpResponse:
        std_data = {
            "code": code,
            "result": data,
            "message": msg,
            "success": True
        }
        content = self.renderer.render(request, std_data, response_status=status)
        content_type = "{}; charset={}".format(
            self.renderer.media_type, self.renderer.charset
        )

        return HttpResponse(content, status=status, content_type=content_type)


class MyPagination(PaginationBase):
    class Input(Schema):
        pageSize: int = Field(10, gt=0)
        page: int = Field(1, gt=-1)

    class Output(Schema):
        items: List[Any]
        total: int

    def paginate_queryset(
            self,
            queryset: QuerySet,
            pagination: Input,
            **params: DictStrAny,
    ) -> Any:
        offset = pagination.pageSize * (pagination.page - 1)
        limit: int = pagination.pageSize
        return {
            "page": offset,
            "limit": limit,
            "items": queryset[offset: offset + limit],
            "total": self._items_count(queryset),
        }  # noqa: E203
